/*************************************************************************
	> File Name: 9-2-server.c
	> Author: Potter
	> Mail: tobewhatwewant@gmail.com
	> Created Time: 2014年09月19日 星期五 15时56分25秒
 ************************************************************************/

#include<stdio.h>
#include<stdlib.h> // int atoi(char * s)
#include<string.h> // extern void bzero(void *s, int n); 置零
#include<netinet/in.h> // unsigned short int htons(unsigned short in hostshort)
#include<sys/socket.h>
// pid_t fork(void);
#include<unistd.h>
#include<sys/types.h>

#include<arpa/inet.h> /* char * inet_ntoa(struct in_addr *)*/

#define BACKLONG 10 // 最大连接数

int main(int argc, char * argv[]) {
    int server_socket, client_socket;
    struct sockaddr_in server_addr;
    struct sockaddr_in client_addr;
    
    char server_response[1024];
    char client_response[1024];

    //
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(atoi(argv[1]));
    server_addr.sin_addr.s_addr = INADDR_ANY;
    bzero(&(server_addr.sin_zero), 8);

    // 1、建立socket
    server_socket = socket(AF_INET, SOCK_STREAM, 0);

    // 2、绑定 bind
    bind(server_socket, (struct sockaddr *)&server_addr, sizeof(struct sockaddr));

    // 3、listen
    listen(server_socket, BACKLONG);

    // 、等待，响应客户端请求
    int from_client_size;
    while(1) {
        from_client_size = sizeof(struct sockaddr_in);
        // 4、相应客户端请求accept
        client_socket = accept(server_socket, (void *)&client_addr, &from_client_size);
        
        fprintf(stdout, "%s 进入:\n", inet_ntoa(client_addr.sin_addr));

        while(recv(client_socket, client_response, 1024, 0) > 0) {
            fprintf(stdout, "client : %s\n", client_response);
        }

        if (! fork()) {
            // 5、发送数据 send
            fprintf(stdout, "\t你相对你的客户说:");
            scanf("%s", server_response);
            send(client_socket, server_response, strlen(server_response), 0);    
           //close(client_socket);
            exit(0);
        }
        // close(client_socket);
    }

    return 0;
}
